package com.gy.spring.mvc.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import com.gy.spring.mvc.common.tools.R;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.gy.spring.mvc.service.HelloService;

import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("hello")
public class HelloController {
    private static Log logger = LogFactory.getLog(HelloController.class);

    @Autowired
    private HelloService helloService;

    @RequestMapping("view")
    public String view() {
        System.out.println("====view.html====");
        return "index";
    }

    @ResponseBody
    @RequestMapping("hello")
    public Object hello() {
        return helloService.hello();
    }

    @ResponseBody
    @RequestMapping("hello/{id}")
    public Object hello(@PathVariable("id") int id) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        HashMap<Object, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("author", "geYang");
        map.put("data", sf.format(new Date()));
        logger.info(map);
        return map;
    }

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public void upload(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception {
        if (!file.isEmpty()) {
            logger.info("file [name:" + file.getOriginalFilename() + ", size:" + file.getSize() + ", fileName:" + file.getName() + ", type:" + file.getContentType() + "]");
            FileCopyUtils.copy(file.getInputStream(), response.getOutputStream());
            //上传的两种方法:
//			FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:/notes/IMGS/image/xx.jpg"));
//			file.transferTo(new File("E:/notes/IMGS/image/xxx.jpg"));
        }
    }

    @GetMapping("test")
    public Object test() {
        helloService.testException();
        return R.ok();
    }

}
